/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#include "arch/locked_mem.hh"
#include "config/the_isa.hh"
#include "config/use_checker.hh"
#include "cpu/edge/lsq.hh"
#include "cpu/edge/lsq_unit.hh"
#include "base/str.hh"
#include "mem/packet.hh"
#include "mem/request.hh"

template<class Impl>
EdgeLSQUnit<Impl>::WritebackEvent::WritebackEvent(DynInstPtr &_inst, PacketPtr _pkt,
                                              EdgeLSQUnit *lsq_ptr)
    : inst(_inst), pkt(_pkt), lsqPtr(lsq_ptr)
{
    this->setFlags(Event::AutoDelete);
}

template<class Impl>
void
EdgeLSQUnit<Impl>::WritebackEvent::process()
{
    if (!lsqPtr->isSwitchedOut()) {
        lsqPtr->writeback(inst, pkt);
    }

    if (pkt->senderState)
        delete pkt->senderState;

    delete pkt->req;
    delete pkt;
}

template<class Impl>
const char *
EdgeLSQUnit<Impl>::WritebackEvent::description() const
{
    return "Store writeback";
}

template<class Impl>
void
EdgeLSQUnit<Impl>::completeDataAccess(PacketPtr pkt)
{
    LSQSenderState *state = dynamic_cast<LSQSenderState *>(pkt->senderState);
    DynInstPtr inst = state->inst;

    DPRINTF(EdgeExe, "Writeback event [Bid:%lli][Iid:%lli][LSID:%i]\n",
               inst->getBlockID(), inst->getInstID(), inst->staticInst->getLSID());
    DPRINTF(Activity, "Activity: Writeback event [sn:%lli]\n", inst->seqNum);

    assert(!pkt->wasNacked());

    if (isSwitchedOut() || inst->isSquashed() ||
        (inst->isLoad() && inst->isBlockCompleted())) {

        DPRINTF(EdgeExe, "Switch out or squashed or block "
            "completed inst encounted\n");
    }else {
        if (!state->noWB) {

            if (!inst->isForward()) {
                // No forward case, just writeback load results.
                DPRINTF(EdgeLSQUnit, "Load has no forward.\n");
                writeback(inst, pkt);
            } else {
                // Forwarding case, handle it.
                DPRINTF(EdgeLSQUnit, "Load has forward.\n");
                uint8_t p[8];
                pkt->writeData(&(p[0]));

                // Check which byte has forwarding data.
                for (int i = 0 ; i < Impl::MaxByteNum ; ++i) {
                    if(inst ->isForward(i)){
                        p[i] = inst->getForwardedData(i);
                        DPRINTF(EdgeLSQUnit, "Load has forward."
                                " Forward data[%i]:%x\n",
                                i, p[i]);
                    }
                }
                // Write back data.
                pkt ->setData(&(p[0]));
                writeback(inst, pkt);
            }
        }
        // Handling store inst.
        if (inst->isStore()) {
            completeStore(state->idx);
        }
    }

    delete state;
    delete pkt->req;
    delete pkt;
}

template <class Impl>
EdgeLSQUnit<Impl>::EdgeLSQUnit()
    : loads(0), stores(0), storesToWB(0), stalled(false),
      isStoreBlocked(false), isLoadBlocked(false),
      loadBlockedHandled(false)
{
}

template<class Impl>
void
EdgeLSQUnit<Impl>::init(CPU *cpu_ptr, Execute *execute_ptr, DerivEdgeCPUParams *params,
        LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
        unsigned id)
{
    cpu = cpu_ptr;
    executeStage = execute_ptr;

    DPRINTF(EdgeLSQUnit, "Creating EdgeLSQUnit%i object.\n",id);

    switchedOut = false;

    lsq = lsq_ptr;

    lsqID = id;

    // Add 1 for the sentinel entry (they are circular queues).
    LQEntries = maxLQEntries + 1;
    SQEntries = maxSQEntries + 1;

    loadQueue.resize(LQEntries);
    storeQueue.resize(SQEntries);

    loadHead = loadTail = 0;

    storeHead = storeWBIdx = storeTail = 0;

    usedPorts = 0;
    cachePorts = params->cachePorts;

    retryPkt = NULL;
    memDepViolator = NULL;

    blockedLoadSeqNum = 0;
}

template<class Impl>
std::string
EdgeLSQUnit<Impl>::name() const
{
    if (Impl::MaxThreads == 1) {
        return executeStage->name() + ".lsq";
    } else {
        return executeStage->name() + ".lsq.thread." + to_string(lsqID);
    }
}

template<class Impl>
void
EdgeLSQUnit<Impl>::regStats()
{
    lsqAllForwLoads
        .name(name() + ".allForwLoads")
        .desc("Number of loads that had all data forwarded from stores");

    lsqPartialForwLoads
        .name(name() + ".partiallForwLoads")
        .desc("Number of loads that had partial data forwarded from stores");

    lsqSquashedLoads
        .name(name() + ".squashedLoads")
        .desc("Number of loads squashed");

    lsqIgnoredResponses
        .name(name() + ".ignoredResponses")
        .desc("Number of memory responses ignored because the instruction is squashed");

    lsqSquashedStores
        .name(name() + ".squashedStores")
        .desc("Number of stores squashed");

    lsqRescheduledLoads
        .name(name() + ".rescheduledLoads")
        .desc("Number of loads that were rescheduled");

    lsqCacheBlocked
        .name(name() + ".cacheBlocked")
        .desc("Number of times an access to memory failed due to the cache being blocked");
}

template<class Impl>
void
EdgeLSQUnit<Impl>::setDcachePort(Port *dcache_port)
{
    dcachePort = dcache_port;

#if USE_CHECKER
    if (cpu->checker) {
        cpu->checker->setDcachePort(dcachePort);
    }
#endif
}

template<class Impl>
void
EdgeLSQUnit<Impl>::clearLQ()
{
    loadQueue.clear();
}

template<class Impl>
void
EdgeLSQUnit<Impl>::clearSQ()
{
    storeQueue.clear();
}

template<class Impl>
void
EdgeLSQUnit<Impl>::switchOut()
{
    switchedOut = true;
    for (int i = 0; i < loadQueue.size(); ++i) {
        assert(!loadQueue[i]);
        loadQueue[i] = NULL;
    }

    assert(storesToWB == 0);
}

template<class Impl>
void
EdgeLSQUnit<Impl>::takeOverFrom()
{
    switchedOut = false;
    loads = stores = storesToWB = 0;

    loadHead = loadTail = 0;

    storeHead = storeWBIdx = storeTail = 0;

    usedPorts = 0;

    memDepViolator = NULL;

    blockedLoadSeqNum = 0;

    stalled = false;
    isLoadBlocked = false;
    loadBlockedHandled = false;
}

template<class Impl>
void
EdgeLSQUnit<Impl>::resizeLQ(unsigned size)
{
    unsigned size_plus_sentinel = size + 1;
    assert(size_plus_sentinel >= LQEntries);

    if (size_plus_sentinel > LQEntries) {
        while (size_plus_sentinel > loadQueue.size()) {
            DynInstPtr dummy;
            loadQueue.push_back(dummy);
            LQEntries++;
        }
    } else {
        LQEntries = size_plus_sentinel;
    }

}

template<class Impl>
void
EdgeLSQUnit<Impl>::resizeSQ(unsigned size)
{
    unsigned size_plus_sentinel = size + 1;
    if (size_plus_sentinel > SQEntries) {
        while (size_plus_sentinel > storeQueue.size()) {
            SQEntry dummy;
            storeQueue.push_back(dummy);
            SQEntries++;
        }
    } else {
        SQEntries = size_plus_sentinel;
    }
}

template <class Impl>
void
EdgeLSQUnit<Impl>::insert(DynInstPtr &inst)
{
    assert(inst->isMemRef());

    assert(inst->isLoad() || inst->isStore());

    if (inst->isLoad()) {
        insertLoad(inst);
    } else {
        insertStore(inst);
    }

    inst->setInLSQ();
}

template <class Impl>
void
EdgeLSQUnit<Impl>::insertLoad(DynInstPtr &load_inst)
{
    assert((loadTail + 1) % LQEntries != loadHead);
    assert(loads < LQEntries);

    DPRINTF(EdgeLSQUnit, "Inserting load PC %#x, idx:%i"
            " [Bid:%lli][Iid:%lli][LSID:%i]\n",
            load_inst->readPC(), loadTail,
            load_inst->getBlockID(),
            load_inst->getInstID(),
            load_inst->staticInst->getLSID());

    load_inst->lqIdx = loadTail;

    loadQueue[loadTail] = load_inst;

    incrLdIdx(loadTail);

    ++loads;
}

template <class Impl>
void
EdgeLSQUnit<Impl>::insertStore(DynInstPtr &store_inst)
{
    // Make sure it is not full before inserting an instruction.
    assert((storeTail + 1) % SQEntries != storeHead);
    assert(stores < SQEntries);

    DPRINTF(EdgeLSQUnit, "Inserting store PC %#x, idx:%i"
            " [Bid:%lli][Iid:%lli][LSID:%i]\n",
            store_inst->readPC(), storeTail,
            store_inst->getBlockID(),
            store_inst->getInstID(),
            store_inst->staticInst->getLSID() );

    store_inst->sqIdx = storeTail;

    storeQueue[storeTail] = SQEntry(store_inst);

    incrStIdx(storeTail);

    ++stores;
}

template <class Impl>
typename Impl::DynInstPtr
EdgeLSQUnit<Impl>::getMemDepViolator()
{
    DynInstPtr temp = memDepViolator;

    memDepViolator = NULL;

    return temp;
}

template <class Impl>
unsigned
EdgeLSQUnit<Impl>::numFreeEntries()
{
    unsigned free_lq_entries = LQEntries - loads;
    unsigned free_sq_entries = SQEntries - stores;

    // Both the LQ and SQ entries have an extra dummy entry to differentiate
    // empty/full conditions.  Subtract 1 from the free entries.
    if (free_lq_entries < free_sq_entries) {
        return free_lq_entries - 1;
    } else {
        return free_sq_entries - 1;
    }
}

template <class Impl>
int
EdgeLSQUnit<Impl>::numLoadsReady()
{
    int load_idx = loadHead;
    int retval = 0;

    while (load_idx != loadTail) {
        assert(loadQueue[load_idx]);

        if (loadQueue[load_idx]->readyToIssue()) {
            ++retval;
        }
    }

    return retval;
}

template <class Impl>
Fault
EdgeLSQUnit<Impl>::executeLoad(DynInstPtr &inst)
{
    using namespace TheISA;
    // Execute a specific load.
    Fault load_fault = NoFault;

    DPRINTF(EdgeLSQUnit, "Executing load PC %#x, [sn:%lli]\n",
            inst->readPC(),inst->seqNum);

    assert(!inst->isSquashed() && !inst->isNullified());

    load_fault = inst->initiateAcc();

    // If the instruction faulted, then it will be handled in execute
    // phase where the fault could be propagated through the whole
    // block and finally handled when block committed.
    if (load_fault != NoFault) {
        DPRINTF(EdgeLSQUnit, "Load faulted.\n");
        executeStage->activityThisCycle();
    } else if (!loadBlocked()) {
        assert(inst->effAddrValid);
        int load_idx = inst->lqIdx;
        incrLdIdx(load_idx);
    }

    return load_fault;
}

template <class Impl>
Fault
EdgeLSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
{
    using namespace TheISA;
    // Make sure that a store exists.
    assert(stores != 0);

    int store_idx = store_inst->sqIdx;

    DPRINTF(EdgeLSQUnit, "Executing store PC %#x [sn:%lli]\n",
            store_inst->readPC(), store_inst->seqNum);

    assert(!store_inst->isSquashed());

    int load_idx = loadHead;

    Fault store_fault = store_inst->initiateAcc();

    if (storeQueue[store_idx].size == 0) {
        DPRINTF(EdgeLSQUnit,"Fault on Store PC %#x, [sn:%lli],Size = 0\n",
                store_inst->readPC(),store_inst->seqNum);

        return store_fault;
    }

    assert(store_fault == NoFault);

    if (store_inst->isStoreConditional()) {
        // Store conditionals need to set themselves as able to
        // writeback if we haven't had a fault by here.
        storeQueue[store_idx].canWB = true;

        ++storesToWB;
    }

    // Check for Load/Store violation
    // Firstly, figure out the idx in LQ that could lead to
    // a violation.
    while (load_idx != loadTail) {
        // Find the idx of load inst that can not executed before this
        // store inst. In the same block, all the load inst having greater
        // LSID than this store can not executed before this store.
        if ((loadQueue[load_idx]->getBlockID() == store_inst->getBlockID())&&
            (loadQueue[load_idx]->staticInst ->getLSID() >
            store_inst->staticInst ->getLSID())) {

            break;
        }

        // All the load inst in the younger block can not executed
        // before this store.
        if (loadQueue[load_idx]->getBlockID() > store_inst->getBlockID()) {
            
            break;
        }

        incrLdIdx(load_idx);
    }

    assert(store_inst->effAddrValid);

    return store_fault;
}

template<class Impl>
void
EdgeLSQUnit<Impl>::nullifyStore(DynInstPtr &inst)
{
    int store_idx = inst->sqIdx;

    DPRINTF(EdgeLSQUnit, "Nullify store with PC@%lli and LSID %i"
            " in store queue %i.\n",
            inst->readPC(),
            inst->staticInst->getLSID(),
            store_idx);

    storeQueue[store_idx].nullified = true;
}

template <class Impl>
void
EdgeLSQUnit<Impl>::commitInstBlock(BlockID blockID)
{
    for (int idx=0; idx < loadQueue.size(); ++idx) {
        if (loadQueue[idx]->getBlockID() <= blockID) {
            loadQueue[idx] = NULL;
            --loads;
        }
    }
    for (int idx=0 ; idx < storeQueue.size(); ++idx) {
        if (storeQueue[idx].inst ->getBlockID() <= blockID) {
            storeQueue[idx].canWB = true;
            ++storesToWB;
        }
    }
}

template <class Impl>
void
EdgeLSQUnit<Impl>::commitLoad()
{
    assert(loadQueue[loadHead]);

    DPRINTF(EdgeLSQUnit, "Committing head load instruction, PC %#x\n",
            loadQueue[loadHead]->readPC());

    if (!loadQueue[loadHead]->isExecuted() &&
        loadQueue[loadHead]->isBlockCompleted()) {

        DPRINTF(EdgeLSQUnit, "Unexecuted load when commit,"
            " complete it in memDepUnit.\n");

        //executeStage->instQueue.completeMemInst(loadQueue[loadHead]);
        executeStage->completeMemInst(loadQueue[loadHead]);
    }

    loadQueue[loadHead] = NULL;

    incrLdIdx(loadHead);

    --loads;
}

template <class Impl>
void
EdgeLSQUnit<Impl>::commitLoads(BlockID blockID)
{
    assert(loads == 0 || loadQueue[loadHead]);

    while (loads != 0 && loadQueue[loadHead]->getBlockID() <= blockID) {
        commitLoad();
    }
}

template <class Impl>
void
EdgeLSQUnit<Impl>::commitStores(BlockID blockID)
{
    assert(stores == 0 || storeQueue[storeHead].inst);

    int store_idx = storeHead;

    while (store_idx != storeTail) {
        assert(storeQueue[store_idx].inst);
        // Mark any stores that are now committed and have not yet
        // been marked as able to write back.
        if (!storeQueue[store_idx].canWB) {
            if ((storeQueue[store_idx].inst)->getBlockID() <= blockID) {
                storeQueue[store_idx].canWB = true;
                ++storesToWB;
            }
        }
        incrStIdx(store_idx);
    }
}

template <class Impl>
void
EdgeLSQUnit<Impl>::writebackStores()
{
    DPRINTF(EdgeLSQUnit,"store head=%d,store tail = %d, store wbidx=%d.\n",
        storeHead,storeTail,storeWBIdx);

    while (storesToWB > 0 &&
           storeWBIdx != storeTail &&
           storeQueue[storeWBIdx].inst &&
           storeQueue[storeWBIdx].canWB &&
           usedPorts < cachePorts) {

        DPRINTF(EdgeLSQUnit,"%d stores to write back.\n",storesToWB);

        // Stores have been nullified, can not write back.
        if (storeQueue[storeWBIdx].nullified) {
            DPRINTF(EdgeLSQUnit, "Nullified store!\n");
            completeStore(storeWBIdx);
            incrStIdx(storeWBIdx);
            continue;
        }

        if (!storeQueue[storeWBIdx].inst->isExecuted()&&
            storeQueue[storeWBIdx].inst->isBlockCompleted()) {

            DPRINTF(EdgeLSQUnit, "Unexecuted store with block completed encounted."
                "Complete it in memDepUnit. \n");

            // This means the store hasn't executed because of
            // predication ( multi stores have the same LSID ).
            // We have to complete the unexecuted inst in
            // memDepUnit here.
            //executeStage->instQueue.completeMemInst(storeQueue[storeWBIdx].inst);
            executeStage->completeMemInst(storeQueue[storeWBIdx].inst);
            
            completeStore(storeWBIdx);
            incrStIdx(storeWBIdx);
            continue;

        }

        if (isStoreBlocked || lsq->cacheBlocked()) {

            DPRINTF(EdgeLSQUnit, "Unable to write back any more stores, cache"
                    " is blocked!\n");
            break;
        }

        // Store didn't write any data so no need to write it back to
        // memory.
        if (storeQueue[storeWBIdx].size == 0) {
            DPRINTF(EdgeLSQUnit, "Store has no data to write back.\n");
            completeStore(storeWBIdx);
            incrStIdx(storeWBIdx);
            continue;
        }

        ++usedPorts;

        if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
            incrStIdx(storeWBIdx);

            continue;
        }

        assert(storeQueue[storeWBIdx].req);
        assert(!storeQueue[storeWBIdx].committed);

        DynInstPtr inst = storeQueue[storeWBIdx].inst;

        Request *req = storeQueue[storeWBIdx].req;
        storeQueue[storeWBIdx].committed = true;

        assert(!inst->memData);
        inst->memData = new uint8_t[64];

        memcpy(inst->memData, storeQueue[storeWBIdx].data, req->getSize());

        MemCmd command =
            req->isSwap() ? MemCmd::SwapReq :
            (req->isLLSC() ? MemCmd::StoreCondReq : MemCmd::WriteReq);
        PacketPtr data_pkt = new Packet(req, command,
                                        Packet::Broadcast);
        data_pkt->dataStatic(inst->memData);

        LSQSenderState *state = new LSQSenderState;
        state->isLoad = false;
        state->idx = storeWBIdx;
        state->inst = inst;
        data_pkt->senderState = state;

        DPRINTF(EdgeLSQWriteBack, "D-Cache: Writing back store idx:%i PC:%#x "
                " %i bytes to physical Addr:%#x[Vaddr:%#x], data:%#x [sn:%lli]\n",
                storeWBIdx, inst->readPC(), req->getSize(),
                req->getPaddr(), req->getVaddr(),
                TheISA::gtoh((*(uint64_t *)inst->memData)),
                inst->seqNum);


        // Store do not need a writeback.
        state->noWB = true;

        if (!dcachePort->sendTiming(data_pkt)) {
            // Need to handle becoming blocked on a store.
            DPRINTF(EdgeExe, "D-Cache became blocked when writing [sn:%lli], will"
                    "retry later\n",
                    inst->seqNum);
            isStoreBlocked = true;
            ++lsqCacheBlocked;
            assert(retryPkt == NULL);
            retryPkt = data_pkt;
            lsq->setRetryTid(lsqID);
        } else {
            DPRINTF(EdgeLSQUnit,"Store send pkt.\n");
            storePostSend(data_pkt);
        }
    }

    // Not sure this should set it to 0.
    usedPorts = 0;

    assert(stores >= 0 && storesToWB >= 0);
}

template <class Impl>
void
EdgeLSQUnit<Impl>::squash(const TheISA::BlockID &squashed_num)
{
    DPRINTF(EdgeLSQUnit, "Squashing until [Bid:%lli]!"
            "(Loads:%i Stores:%i)\n",
            squashed_num,
            loads,
            stores);

    int load_idx = loadTail;
    decrLdIdx(load_idx);

    while (loads != 0 && loadQueue[load_idx]->getBlockID() > squashed_num) {
        DPRINTF(EdgeLSQUnit,"Load Instruction PC %#x squashed, "
                "[Bid:%lli][Iid:%lli]\n",
                loadQueue[load_idx]->readPC(),
                loadQueue[load_idx]->getBlockID(),
                loadQueue[load_idx]->getInstID());

        if (isStalled() && load_idx == stallingLoadIdx) {
            stalled = false;
            stallingStoreIsn = 0;
            stallingLoadIdx = 0;
        }

        // Clear the smart pointer to make sure it is decremented.
        loadQueue[load_idx]->setSquashed();
        loadQueue[load_idx] = NULL;
        --loads;

        // Inefficient!
        loadTail = load_idx;

        decrLdIdx(load_idx);
        ++lsqSquashedLoads;
    }

    if (isLoadBlocked) {
        if (squashed_num < blockedLoadSeqNum) {
            isLoadBlocked = false;
            loadBlockedHandled = false;
            blockedLoadSeqNum = 0;
        }
    }

    if (memDepViolator && squashed_num < memDepViolator->seqNum) {
        memDepViolator = NULL;
    }

    int store_idx = storeTail;
    decrStIdx(store_idx);

    while (stores != 0 &&
           storeQueue[store_idx].inst->getBlockID() > squashed_num) {
        // Instructions marked as can WB are already committed.
        if (storeQueue[store_idx].canWB) {
            break;
        }

        DPRINTF(EdgeLSQUnit,"Store Instruction PC %#x squashed, "
                "idx:%i [Bid:%lli][Iid:%lli]\n",
                storeQueue[store_idx].inst->readPC(),
                store_idx, storeQueue[store_idx].inst->getBlockID(),
                storeQueue[store_idx].inst->getInstID() );

        // I don't think this can happen.  It should have been cleared
        // by the stalling load.
        if (isStalled() &&
            storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
            panic("Is stalled should have been cleared by stalling load!\n");
            stalled = false;
            stallingStoreIsn = 0;
        }

        // Clear the smart pointer to make sure it is decremented.
        storeQueue[store_idx].inst->setSquashed();
        storeQueue[store_idx].inst = NULL;
        storeQueue[store_idx].canWB = 0;

        // Must delete request now that it wasn't handed off to
        // memory.  This is quite ugly.  @todo: Figure out the proper
        // place to really handle request deletes.
        delete storeQueue[store_idx].req;

        storeQueue[store_idx].req = NULL;
        --stores;

        // Inefficient!
        storeTail = store_idx;

        decrStIdx(store_idx);
        ++lsqSquashedStores;
    }
}

template <class Impl>
void
EdgeLSQUnit<Impl>::storePostSend(PacketPtr pkt)
{
    if (isStalled() &&
        storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
        DPRINTF(EdgeLSQUnit, "Unstalling, stalling store [sn:%lli] "
                "load idx:%i\n",
                stallingStoreIsn, stallingLoadIdx);
        stalled = false;
        stallingStoreIsn = 0;
        executeStage->replayMemInst(loadQueue[stallingLoadIdx]);
    }

    if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
        // The store is basically completed at this time. This
        // only works so long as the checker doesn't try to
        // verify the value in memory for stores.
        storeQueue[storeWBIdx].inst->setCompleted();
    }

    incrStIdx(storeWBIdx);
}

template <class Impl>
void
EdgeLSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
{
    executeStage->wakeCPU();

    assert(inst->isMemRef());
    assert(inst->isLoad());

    // Squashed instructions do not need to complete their access.
    if (inst->isSquashed() || inst->isBlockCompleted() ) {

        DPRINTF(EdgeLSQUnit, "Squashed or block completed "
                "load[Bid:%lli][Iid:%lli][LSID:%i] encounterd.\n",
                inst->getBlockID(),
                inst->getInstID(),
                inst->staticInst->getLSID() );

        assert(!inst->isStore());
        ++lsqIgnoredResponses;
        return;
    }

    if (!inst->isExecuted()) {
        inst->setExecuted();

        assert(inst->isMemRef());

        DPRINTF(EdgeLSQWriteBack,"Load from %i bytes p:%#x[v:%#x]"
                " with data %#x\n",
                pkt->getSize(),
                pkt->req->getPaddr(),
                pkt->req->getVaddr(),
                TheISA::gtoh(*(uint64_t*)pkt->getPtr<uint8_t>()));

        // Complete access to copy data to proper place.
        inst->completeAcc(pkt);
    }

    // Load write-back, wake up dependents.
    //executeStage->instQueue.wakeDependents(inst);
    executeStage->wakeDependents(inst);

    executeStage->activityThisCycle();
}

template <class Impl>
void
EdgeLSQUnit<Impl>::completeStore(int store_idx)
{
    assert(storeQueue[store_idx].inst);
    storeQueue[store_idx].completed = true;
    --storesToWB;
    DPRINTF(EdgeLSQUnit,"Store[LSID:%i] is completed.\n",
    storeQueue[store_idx].inst->staticInst->getLSID());

    // A bit conservative because a store completion may not free up entries,
    // but hopefully avoids two store completions in one cycle from making
    // the CPU tick twice.
    cpu->wakeCPU();
    cpu->activityThisCycle();

    DPRINTF(EdgeLSQUnit, "Completing store [sn:%lli], idx:%i, store head "
            "idx:%i\n",
            storeQueue[store_idx].inst->seqNum, store_idx, storeHead);

    if (isStalled() &&
        storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
        DPRINTF(EdgeLSQUnit, "Unstalling, stalling store [sn:%lli] "
                "load idx:%i\n",
                stallingStoreIsn, stallingLoadIdx);
        stalled = false;
        stallingStoreIsn = 0;
        executeStage->replayMemInst(loadQueue[stallingLoadIdx]);
    }

    storeQueue[store_idx].inst->setCompleted();

    if (store_idx == storeHead) {
        do {
            // Delete this reference.
            storeQueue[storeHead].inst = NULL;

            incrStIdx(storeHead);

            --stores;
        } while (storeQueue[storeHead].completed &&
                 storeHead != storeTail);

        executeStage->updateLSQNextCycle = true;
    }
}

template <class Impl>
void
EdgeLSQUnit<Impl>::recvRetry()
{
    if (isStoreBlocked) {
        DPRINTF(EdgeLSQUnit, "Receiving retry: store blocked\n");
        assert(retryPkt != NULL);

        if (dcachePort->sendTiming(retryPkt)) {
            storePostSend(retryPkt);
            retryPkt = NULL;
            isStoreBlocked = false;
            lsq->setRetryTid(InvalidThreadID);
        } else {
            // Still blocked!
            ++lsqCacheBlocked;
            lsq->setRetryTid(lsqID);
        }
    } else if (isLoadBlocked) {
        DPRINTF(EdgeLSQUnit, "Loads will be replayed, "
                "no need to resend packet.\n");
    } else {
        DPRINTF(EdgeLSQUnit, "Retry received but LSQ is no longer blocked.\n");
    }
}

template <class Impl>
void
EdgeLSQUnit<Impl>::dumpInsts()
{
    cprintf("Load store queue: Dumping instructions.\n");
    cprintf("Load queue size: %i\n", loads);
    cprintf("Load queue: ");

    int load_idx = loadHead;

    while (load_idx != loadTail && loadQueue[load_idx]) {
        cprintf("%#x ", loadQueue[load_idx]->readPC());

        incrLdIdx(load_idx);
    }

    cprintf("Store queue size: %i\n", stores);
    cprintf("Store queue: ");

    int store_idx = storeHead;

    while (store_idx != storeTail && storeQueue[store_idx].inst) {
        cprintf("%#x ", storeQueue[store_idx].inst->readPC());

        incrStIdx(store_idx);
    }

    cprintf("\n");
}
